package com.softserveinc.ita.kaiji.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.softserveinc.ita.kaiji.model.User;

/**
 * @author Eugene Semenkov
 * @version 1.0
 * @since 01.04.14
 */

@Repository
public class UserHibernateImplDAO implements UserHibernateDAO {
	
	private Session session;
	private SessionFactory sessionFacroty;
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFacroty) {
		this.sessionFacroty = sessionFacroty;
		this.session = sessionFacroty.openSession();
	}

	@Override
	public Integer add(User user) {
		
		if(user.getName() == null) {
			return null;
		}
		
		if(this.getById(user.getId()) == null) {
			return null;
		}
		
		session.save(user);
		return user.getId();
	}

	@Override
	public User getById(Integer id) {
		
		Query query = session.createQuery("from UserImpl where id=?");
		query.setInteger(0, id);
		
		List<User> list = (List<User>)query.list();
		
		if(list == null) {
			return null;
		}	
		
		if(list.size() == 0) {
			return null;
		}
		
		return list.get(0);
		
	}

	@Override
	public User getByName(String name) {
		
		Query query = session.createQuery("from UserImpl where name=?");
		query.setString(0, name);
		
		List<User> list = (List<User>)query.list();
		
		if(list == null) {
			return null;
		}
		
		if(list.size() == 0) {
			return null;
		}
		
		return list.get(0);
		
	}

	@Override
	public boolean update(User user) {
		
		if(user.getId() == null || user.getName() == null) {
			return false;
		}
		
		if(this.getById(user.getId()) == null) {
			return false;
		}		

		session.merge(user);
		session.flush();
		return true;
		
	}

	@Override
	public boolean remove(User user) {
		
		if(user.getId() == null) {
			return false;
		}
		
		if(this.getById(user.getId()) == null) {
			return false;
		}		
		
		Query query=session.createQuery("delete UserImpl where id=? ");
		query.setInteger(0,user.getId());
		query.executeUpdate();
		return true;
	}

}
